package com.zhifou.aspect;

import cn.hutool.core.util.StrUtil;
import com.zhifou.annotation.NoRepeatSubmit;
import com.zhifou.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author 公众号 知否技术
 * @description TODO
 * @date 2023-02-23 16:33
 */
@Aspect
@Component
@Slf4j
public class NoRepeatSubmitAspect {

    @Autowired
    private RedissonClient redissonClient;

    private static final String REDISSON_LOCK_PREFIX = "redisson_lock:";

    @Around("@annotation(noRepeatSubmit)")
    public Object noRepeatSubmitAop(ProceedingJoinPoint joinPoint, NoRepeatSubmit noRepeatSubmit) throws Throwable {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        String lockName = REDISSON_LOCK_PREFIX + joinPoint.getTarget().getClass().getName() + StrUtil.COLON + targetMethod.getName();
        log.info("lockName----->{}", lockName);
        RLock lock = redissonClient.getLock(lockName);
        // 参数：等待时间、过期时间、过期时间单位-毫秒
        boolean flag = lock.tryLock(0, noRepeatSubmit.timeout(), TimeUnit.MILLISECONDS);
        if (!flag) {
            return Result.fail("请勿重复操作");
        }
        return joinPoint.proceed();
    }

}
